<template>
  <div class="box">

    <!-- 错误提示 -->
    <SvgIcon v-if="error" icon="icon-park-outline:error-picture" style="font-size: 30px;color: rgb(245, 34, 45);" />
    <img v-if="blobUrl" :src="blobUrl" :alt="altText" :style="imgStyle" :onerror="handleImageError" />
  </div>
</template>

<script setup lang="ts">
import { getToken, serveConfig } from "@/axios-utils";
import { localStg } from "@/utils/storage";
import SvgIcon from "@/components/custom/svg-icon.vue";
import { computed, defineComponent, onMounted, onUnmounted, ref, watch } from "vue";
const props = defineProps({
  url: {
    type: String,
    required: true
  },
  altText: {
    type: String,
    default: 'Protected image'
  },
  maxHeight: {
    type: [Number, null],
  },
  maxWidth: {
    type: [Number, null],
  }
});

const imgStyle = computed(() => {
  return {
    maxWidth: props.maxWidth ? `${props.maxWidth}px` : '100%',
    maxHeight: props.maxHeight ? `${props.maxHeight}px` : '100%',
  };
})
const blobUrl = ref<string | null>();
const loading = ref(false)
const error = ref<string | null>();
const fetchImage = () => {
  loading.value = true
  error.value = null
  cleanupBlobUrl();
  fetch(props.url, {
    headers: {
      Authorization: `Bearer ${getToken()}`,
    },
  })
    .then((response) => {
      return response.blob()
    })
    .then((blob) => {
      // 创建一个 URL 对象，用于表示 blob 对象的 URL
      blobUrl.value = URL.createObjectURL(blob);
    }).catch((err) => {
      error.value = '图片加载失败';
    }).finally(() => {
      loading.value = false
    })

}
watch(() => props.url, (newUrl) => {
  if (!newUrl) {
    return;
  }
  fetchImage();
})

onMounted(() => {
  fetchImage();
})
// 组件挂载时自动加载
onUnmounted(() => {
  cleanupBlobUrl()
})

// 图片加载错误处理
const handleImageError = () => {
  error.value = '图片加载失败'
  cleanupBlobUrl();
}
const cleanupBlobUrl = () => {
  if (blobUrl.value) {
    URL.revokeObjectURL(blobUrl.value)
    blobUrl.value = null
  }
}

</script>

<style scoped>
.box {
  display: flex;
  justify-content: center;
  align-items: center;
}

.child {
  text-align: center;
  /* 子元素内文本水平居中（可选） */
}
</style>
